package com.hao.view;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.OvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hao.viewdemo.R;

/**
 * Created by hao on 16/10/20.
 */
public class WithGesturesView extends LinearLayout {

    private static final String TAG = WithGesturesView.class.getSimpleName();

    public interface OnScrollOut {
        void delete(View view);
    }

    private OnScrollOut onScrollOut;


    private static final int ZOOM_SIZE = 20;

    private LayoutInflater layoutInflater;

    private ImageView imageView;

    private TextView textView;


    private int zoomWidth = 0;
    private int zoomHeight = 0;
    //初始的控件 左 上 位置 记忆
    private int initialLife = 0;
    private int initialTop = 0;
    //结束的控件 左 上 位置 记忆
    private int endLife = 0;
    private int endTop = 0;
    //辅助 左  上 位置记忆
    private int auxiliaryLife = 0;
    private int auxiliaryTop = 0;
    //按下 与  原来 间隔
    private int deviationX = 0;
    private int deviationY = 0;
    //控件的长度和宽度
    private int width = 0;
    private int hight = 0;
    //屏幕的长 宽
    private int screenWidth = 0;
    private int screenHeight = 0;
    //todo title的高度 免影响 -》强调 这里才用的是整个屏幕的坐标  不是先对于父控件的坐标
    private int topTitleHeight = 0; //如果有的话 要处理

    private boolean isFocus = false;

    public void setOnScrollOut(OnScrollOut onScrollOut) {
        this.onScrollOut = onScrollOut;
    }

    public void setFocus(boolean focus) {
        this.isFocus = focus;
    }

    public WithGesturesView(Context context) {
        this(context, null);
    }

    public WithGesturesView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WithGesturesView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        screenWidth = getScreenWidth(context);
        screenHeight = getScreenHeight(context);
        layoutInflater = LayoutInflater.from(context);
        layoutInflater.inflate(R.layout.with_gestures_view, this);
        imageView = (ImageView) findViewById(R.id.head);
        textView = (TextView) findViewById(R.id.content);
    }

    /**
     * 设置图片 和名字
     *
     * @param imageId 资源id
     * @param content 内容
     */
    public void setIamgeText(@DrawableRes int imageId, String content) {
        imageView.setImageResource(imageId);
        textView.setText(content);
    }

    /**
     * 设置图片 和名字
     * todo 暂时不处理
     *
     * @param imURL   资源imURL
     * @param content 内容
     */
    public void setIamgeText(String imURL, String content) {
//        imageView.setImageResource(imageId);
        textView.setText(content);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = getWidth();
        hight = getHeight();
        zoomWidth = width + ZOOM_SIZE;
        zoomHeight = hight + ZOOM_SIZE;
    }


    private int outX = 0;
    private int downX = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isFocus)
            return false;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) event.getX();
                deviationX = (int) event.getRawX() - auxiliaryLife;
                deviationY = (int) event.getRawY() - auxiliaryTop;
                break;
            case MotionEvent.ACTION_UP:
                if (endLife != 0 && Math.abs(initialLife - endLife) - width / 2 > 0) {
                    if (onScrollOut != null) {
                        onScrollOut.delete(WithGesturesView.this);
                        return true;
                    }
                }
                slideview(0, initialLife - endLife, 0, initialTop - endTop);
                break;
            case MotionEvent.ACTION_MOVE:
                moveViewByLayout((int) event.getRawX(), (int) event.getRawY());
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (initialLife == 0)
            initialLife = l;
        if (initialTop == 0)
            initialTop = t;
        auxiliaryLife = l;
        auxiliaryTop = t;
    }

    /**
     * 通过layout方法，移动view
     * 优点：对view所在的布局，要求不苛刻，不要是RelativeLayout，而且可以修改view的大小
     *
     * @param rawX
     * @param rawY
     */

    private void moveViewByLayout(int rawX, int rawY) {
        int left = rawX - deviationX;
        int top = rawY - deviationY;
        int width = left + this.width;
        int height = top + this.hight;
        layout(left, top, width, height);
        endLife = left;
        endTop = top;
    }


    public void slideview(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta) {
        TranslateAnimation animation = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta);
        animation.setInterpolator(new OvershootInterpolator());
        animation.setDuration(2000);
        animation.setStartOffset(0);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                clearAnimation();
                layout(initialLife, initialTop, initialLife + width, initialTop + hight);
            }
        });
        startAnimation(animation);
    }


    /**
     * 获取屏幕的宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    /**
     * 获取屏幕的高度
     *
     * @param context
     * @return
     */

    public static int getScreenHeight(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

}
